import { Form, Input, Button, Space, Message } from '@arco-design/web-react';
import { FormInstance } from '@arco-design/web-react/es/Form';
import { IconLock, IconUser } from '@arco-design/web-react/icon';
import React, { useCallback, useRef, useState } from 'react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import styles from './style/index.module.less';
import { useHistory } from 'react-router-dom';
import { loginApi } from '@/api/loginData';
import qs from 'qs';
import { guid } from '@/utils/common';

function LoginForm({ onResetPwd }) {
  const formRef = useRef<FormInstance>();
  const [loading, setLoading] = useState(false);

  const t = useLocale(locale);

  const history = useHistory();

  const login = useCallback(async (params) => {
    const hostname = window.location.hostname.split('.');
    const subdomain =
      process.env.NODE_ENV == 'development' ? '' : hostname[0];

    const reqData = {
      client_id: 'ctl_enterprise',
      //client_secret: 'ctl_enterprise_secret',
      grant_type: 'password',
      enterprise_subdomains: subdomain,
      ...params,
    };
    setLoading(true);
    const res: any = await loginApi(qs.stringify(reqData));

    if (res.StatusCode === 200) {
      localStorage.setItem('token_type', res.token_type);
      localStorage.setItem('token', res.access_token);
      localStorage.setItem('userName', reqData.username);
      localStorage.setItem('enterpriseCode', res.enterpriseCode);

      // 记录登录状态
      localStorage.setItem('userStatus', 'login');

      // 判断是否需要重置密码
      if (res.IsValid) {
        Message.success('登录成功');
        setLoading(false);
        history.push({
          pathname: '/',
        });
      } else {
        setLoading(false);
        // 去重置密码
        onResetPwd();
        formRef.current?.resetFields();
      }
    } else {
      setLoading(false);
      Message.error(res.Message);
    }
  }, []);

  function onSubmitClick() {
    formRef.current.validate().then((values) => {
      login(values);
    });
  }

  return (
    <div className={styles['login-form-wrapper']} style={{ padding: 40 }}>
      <div
        className={styles['login-form-title']}
        style={{ textAlign: 'center' }}
      >
        登录
      </div>

      <Form className={styles['login-form']} layout="vertical" ref={formRef}>
        <Form.Item
          field="username"
          rules={[{ required: true, message: t['login.form.userName.errMsg'] }]}
        >
          <Input
            size="large"
            prefix={<IconUser />}
            placeholder="请输入用户名"
            onPressEnter={onSubmitClick}
            autoComplete={'off'}
          />
        </Form.Item>
        <Form.Item
          field="password"
          rules={[{ required: true, message: t['login.form.password.errMsg'] }]}
        >
          <Input.Password
            size="large"
            prefix={<IconLock />}
            placeholder="请输入密码"
            onPressEnter={onSubmitClick}
            autoComplete={'off'}
          />
        </Form.Item>
        <Space size={16} direction="vertical">
          <Button
            shape="round"
            type="primary"
            long
            onClick={onSubmitClick}
            loading={loading}
            size="large"
          >
            {t['login.form.login']}
          </Button>
        </Space>
      </Form>
    </div>
  );
}

export default LoginForm;
